package src;

import javax.swing.*;
import java.awt.*;
import java.awt.Window;
import java.sql.*;

public class UsageAddDialog extends AddDialog {
    public UsageAddDialog(Window parent, Connection connection) {
        super(parent, "添加用水信息", connection);
        
        // 自动生成账单ID
        String nextBillId = generateNextBillId();
        JTextField billIdField = new JTextField(nextBillId);
        billIdField.setEditable(false);
        addInputField("ID:", billIdField);
        
        // 添加客户下拉框
        JComboBox<String> customerCombo = new JComboBox<>();
        customerCombo.addItem(null);  // 添加一个空选项
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT customer_id, name FROM customer");
            while (rs.next()) {
                String customerId = rs.getString("customer_id");
                String customerName = rs.getString("name");
                customerCombo.addItem(customerName + " (" + customerId + ")");
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载客户信息失败: " + e.getMessage());
        }
        addComboBox("客户:", customerCombo);
        
        addInputField("抄表日期:", new JTextField());
        addInputField("读数:", new JTextField());
        
        // 添加用水类型下拉框
        JComboBox<String> waterTypeCombo = new JComboBox<>();
        waterTypeCombo.addItem(null);  // 添加一个空选项
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT type_name FROM water_type");
            while (rs.next()) {
                waterTypeCombo.addItem(rs.getString("type_name"));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载用水类型失败: " + e.getMessage());
        }
        addComboBox("用水类型:", waterTypeCombo);

        confirmButton.addActionListener(e -> {
            try {
                String waterTypeId = getWaterTypeId(waterTypeCombo.getSelectedItem().toString());
                if (waterTypeId == null) {
                    JOptionPane.showMessageDialog(this, "无效的用水类型！");
                    return;
                }

                // 从客户选择框中提取客户ID
                String selectedCustomer = customerCombo.getSelectedItem().toString();
                String customerId = selectedCustomer.substring(selectedCustomer.lastIndexOf("(") + 1, selectedCustomer.lastIndexOf(")"));

                String sql = "INSERT INTO water_bill (bill_id, customer_id, reading_date, current_reading, water_type_id, last_reading, usage_amount, total_amount, salesman_id) VALUES (?, ?, ?, ?, ?, 0, 0, 0, '')";
                PreparedStatement pstmt = connection.prepareStatement(sql);
                pstmt.setString(1, billIdField.getText());
                pstmt.setString(2, customerId);
                pstmt.setString(3, textFields.get("抄表日期:").getText());
                pstmt.setDouble(4, Double.parseDouble(textFields.get("读数:").getText()));
                pstmt.setString(5, waterTypeId);
                
                pstmt.executeUpdate();
                JOptionPane.showMessageDialog(this, "用水信息添加成功！");
                dispose();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "添加用水信息失败: " + ex.getMessage());
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "读数必须是数字！");
            }
        });
    }

    private String generateNextBillId() {
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT bill_id FROM water_bill ORDER BY bill_id");
            
            if (!rs.next()) {
                return "BILL0001";
            }
            
            java.util.Set<Integer> usedIds = new java.util.HashSet<>();
            do {
                String currentId = rs.getString("bill_id");
                int num = Integer.parseInt(currentId.substring(4));
                usedIds.add(num);
            } while (rs.next());
            
            int nextNum = 1;
            while (usedIds.contains(nextNum)) {
                nextNum++;
            }
            
            return String.format("BILL%04d", nextNum);
            
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "生成账单ID失败: " + e.getMessage());
            return "BILL0001";
        }
    }

    private String getWaterTypeId(String typeName) throws SQLException {
        String sql = "SELECT water_type_id FROM water_type WHERE type_name = ?";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        pstmt.setString(1, typeName);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            return rs.getString("water_type_id");
        }
        return null;
    }
} 